package com.learn.multDataSource.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import javax.sql.XADataSource;
import javax.transaction.UserTransaction;

/**
 * 多数据源 + Atomikos事务(多数据源事务一致性)
 */
@Configuration
public class DataSourceConfig {

    /**
     * mysql数据源（主库）
     * @return AtomikosDataSourceBean
     */
    @Primary
    @Bean(name = "masterDataSource")
    public DataSource dataSource1() {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        ds.setXaDataSource(xaDataSource1());
        return ds;
    }

    /**
     * elastic数据源（搜索库）
     * @return AtomikosDataSourceBean
     */
    @Bean(name = "secondDataSource")
    public DataSource dataSource2() {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        ds.setXaDataSource(xaDataSource2());
        return ds;
    }

    /**
     * 临时
     * mysql数据库（主库）
     * @return DruidXADataSource（Druid）
     */
    @Bean()
    @ConfigurationProperties(prefix = "spring.datasource.master")
    XADataSource xaDataSource1() {
        return new DruidXADataSource();
    }

    /**
     * 临时
     * elastic数据库（搜索库）
     * @return DruidXADataSource（Druid）
     */
    @Bean()
    @ConfigurationProperties(prefix = "spring.datasource.second")
    XADataSource xaDataSource2() {
        return new DruidXADataSource();
    }

    /**
     * 注入事物管理器（统一事务）
     */
    @Bean(name = "transactionManager")
    public JtaTransactionManager regTransactionManager () {
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        UserTransaction userTransaction = new UserTransactionImp();
        return new JtaTransactionManager(userTransaction, userTransactionManager);
    }


}
